﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using MeTalker.Aide;
using MuchInfo.Logs;
using MeTalker.Aide.Forms;
using MeTalker.Aide.data;
using System.Diagnostics;
using System.Reflection;
using MeTalker.SDK.Core;

namespace MeTalker
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            MILog.Init("MeTalker");
            AppDomain currentDomain = AppDomain.CurrentDomain;
            currentDomain.UnhandledException += new UnhandledExceptionEventHandler(ExceptionHandler);
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Process proc = Process.GetCurrentProcess();
            String param = " -pid " + proc.Id + " -language Chinese_Simplified";// +Application.CurrentCulture.Name;
            //WindowControl.ShellExecute(proc.Handle, "open", "Updater.exe", param, AppDomain.CurrentDomain.BaseDirectory, WindowControl.SW_SHOWNORMAL);
            //MeTalker.Aide.Service.HttpClient.RequestHeart("http://my.open.taobao.com/auth/authorize.htm?appkey=12376452", new byte[] { 1 }, 1);
           // Console.WriteLine(DateTime.Parse("2000-12-12").CompareTo(DateTime.Parse("2000-12-13")));

            //Application.Run(new  frmTip("fsfdsdsgfsda"));
            //SerializerFactory.SerializeFile<Top.Api.Response.ItemsListGetResponse>(new Top.Api.Response.ItemsListGetResponse() { Items = new List<Top.Api.Domain.Item>() { new Top.Api.Domain.Item() { DetailUrl = "dsfsd" } } }, "ddxds");

            //  SerializerFactory.SerializeFile<GoodsListItem>(new GoodsListItem { GoodsItems = new List<GoodsItem>() {  new  GoodsItem(){ DetailUrl="sdfsd"}} }, "ddxds.xml");
            //string dd = System.Web.HttpUtility.UrlDecode("http://trade.taobao.com/trade/itemlist/list_sold_items.htm?user_type=1&event_submit_do_query=1&action=itemlist/query_action&_fmt.q._0.au=PAID&_fmt.q._0.b=%79%61%6e%31%36%38%31%33%38");
            //Console.WriteLine(dd);
          //  var d = DataFactory.Tips;
            //MeTalker.Aide.DBUtility.AccessHelper.InsertCustomMsg(new MeTalker.Aide.Forms.Mode.CustomMsg() { CustomName="张三", Time=DateTime.Now.ToString("HH:mm:ss"), Content="你好我要的东东东是" });
            //INit();
            //MeTalker.Aide.data.DataFactory.GetInitialization();
            //UtilHelper.FindAnswer("在?");
            //MeTalker.Aide.DBUtility.AccessHelper.InsertProblem("你好 在", "您好!");
            //MeTalker.Aide.DBUtility.AccessHelper.GetProblemList();
            //MeTalker.Aide.data.DataFactory.GetInitialization();
            //Application.Run(new  frmCustomMessage());
            //Application.Run(new MeTalker.Aide.Forms.frmTypeEdit());
           //Application.Run( new frmQueryOrder("dfgfdddddddddddddddddddd\r\nddddgdfgdfgdfgdfgdffffff", 22));
            //Page();

            //Console.WriteLine("开始:"+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            if (GetRunningInstance() == null)
            {   
                if (new frmLoad().ShowDialog() == DialogResult.Yes && DataFactory.User != null && DataFactory.User.IsSuccess)
                {
                    DataFactory.GetInitialization();
                    Application.Run(new MeAppContext());
                }
            }
            else
            {
                MeMessageBox.ShowInformation("金兰旺旺智能客服已经运行! ");
                //MeMessageBox.ShowInformation(DataFactory.Tips.tip_double_run_str);
                Application.Exit();
            }
            

            //MeTalker.Aide.data.DataFactory.GetInitialization();            
            //Application.Run(new frmTestMenu(MeTalker.Aide.data.DataFactory.Menus.Nodes[0]));

            //Application.Run(new Form1());
            //Application.Run(new frmAutoReply());
            //Application.Run(new TalkerTip());
            //Application.Run(new MeTalker.Aide.Forms.frmMessage());
            //Application.Run(new MeTalker.Aide.Forms.frmTypeEdit());
        }

        public static Process GetRunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            //遍历正在有相同名字运行的例程 
            foreach (Process process in processes)
            {
                //忽略现有的例程 
                if (process.Id != current.Id)
                    //确保例程从EXE文件运行 
                    if (Assembly.GetExecutingAssembly().Location.Replace("/ ", "\\ ") == current.MainModule.FileName)
                        //返回另一个例程实例 
                        return process;
            }
            return null;
        }

        #region 测试
        //static void Page() {

        //    List<string> ss = new List<string>() { "Hjiang", "Hwang", "Wange", "Hwan", "Hcheng", "Hhoho" };

        //   var ds =  ss.Skip(2).Take(20);
        //   foreach (var d in ds) {
        //       Console.WriteLine(d);
        //   }
        //string[] Array = { "Hjiang", "Hwang", "Wange", "Hwan", "Hcheng", "Hhoho" };
        //var sArray = GetIenumberable<String>(Array, r => r!="", r => r, 2, 2);
        //    foreach (var s in sArray)
        //    {
        //        Console.WriteLine(s);
        //    } 
        //}

        //static IEnumerable<T> GetIenumberable<T>(IEnumerable<T> List, Func<T,bool> FunWhere, Func<T, string> FunOrder, int PageSize, int PageIndex)
        //{
        //    var rance = List.Where(FunWhere).OrderByDescending(FunOrder).
        //    Select(t => t).Skip((PageIndex - 1) * PageSize).Take(PageSize);
        //    return rance;
        //} 

        //static void INit() {

        //    MeTalker.Aide.data.MenuNavigation menu = new MeTalker.Aide.data.MenuNavigation();
        //    menu.Nodes.Add( new MeTalker.Aide.data.MessageNode() {  Id=1, Title="菜单列表1", Nodes = new List<Aide.data.Node>() { new MeTalker.Aide.data.Node() { Text = "dsfs", Key = "dsfds" }, new MeTalker.Aide.data.Node() { Text = "dsfs", Key = "dsfds" } } });
        //    menu.Nodes.Add(new MeTalker.Aide.data.MessageNode() { Id=1, Title="菜单列表1" , Nodes = new List<Aide.data.Node>() { new MeTalker.Aide.data.Node() { Text = "dsfs", Key = "dsfds" } } });
        //    menu.Nodes.Add(new MeTalker.Aide.data.MessageNode() {  Id=1, Title="菜单列表1" ,Nodes = new List<Aide.data.Node>() { new MeTalker.Aide.data.Node() { Text = "dsfs", Key = "dsfds" } } });
        //    MeTalker.Aide.data.SerializerFactory.SerializeXml(menu);
        //}

        #endregion

        static void Application_ApplicationExit(object sender, EventArgs e)
        {
            MILog.Info("当前程序已经退出");
        }

        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            MILog.Fatal(sender, e.Exception);
        }

        static void ExceptionHandler(object sender, UnhandledExceptionEventArgs args)
        {
            Exception ex = (Exception)args.ExceptionObject;
            MILog.Fatal(sender, ex);
        }
    }
}